package thread;

import java.util.PriorityQueue;

//定时器任务
class MyTimerTask implements Comparable<MyTimerTask>{
    public long time;
    public Runnable task;

    public MyTimerTask(Runnable task, long time) {
        this.task = task;
        this.time = time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);
    }
}

//模拟实现定时器
public class MyTimer {
    private PriorityQueue<MyTimerTask> queue;
    private final Object locker = new Object();

    public MyTimer() {
        queue = new PriorityQueue<>();
        synchronized (locker) {
            Thread t = new Thread(() -> {
                while(true) {
                    //从队列获取任务
                    while (queue.isEmpty()) {
                        try {
                            locker.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    MyTimerTask task = queue.peek();
                    if (task.time > System.currentTimeMillis()) {
                        try {
                            locker.wait(task.time - System.currentTimeMillis());
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    } else {
                        queue.poll();
                        task.task.run();
                    }
                }
            });
        }
    }

    public void schedule(Runnable task, long delay) {
        synchronized (locker) {
            MyTimerTask myTimerTask = new MyTimerTask(task, System.currentTimeMillis() + delay);
            queue.offer(myTimerTask);
        }
    }
}
